package com.example.braden.answergame.common.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.braden.answergame.R;
import com.example.braden.answergame.common.Constant;
import com.example.braden.answergame.common.ImageLoader;
import com.example.braden.answergame.common.LogUtils;
import com.example.braden.answergame.common.utils.MediaUtil;
import com.example.braden.answergame.component.CardDisplayManager;
import com.example.braden.answergame.modules.main.domain.QuestionEntity;
import com.example.braden.answergame.modules.main.domain.UserStatusEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by braden on 2018/3/2.
 */
public class AnswerCardLayout extends RelativeLayout {

    @BindView(R.id.rl_count_layout)
    RelativeLayout rlCountLayout;
    @BindView(R.id.rl_ready_layout)
    RelativeLayout rlReadyLayout;
    @BindView(R.id.tv_question_content)
    TextView tvQuestionContent;
    @BindView(R.id.option_list)
    ListView optionList;
    @BindView(R.id.rl_qestion_main)
    RelativeLayout rlQestionMain;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.iv_left_right_or_wrong)
    ImageView ivLeftRightOrWrong;
    @BindView(R.id.tv_left_revive)
    TextView tvLeftRevive;
    @BindView(R.id.tv_right_revive)
    TextView tvRightRevive;
    @BindView(R.id.iv_right_right_or_wrong)
    ImageView ivRightRightOrWrong;
    @BindView(R.id.tv_prop_tips)
    TextView tvPropTips;
    @BindView(R.id.tv_yanshi_tips)
    CountdownView tvYanshiTips;
    @BindView(R.id.tv_self_yanshi)
    TextView tvSelfYanshi;
    //@BindView(R.id.btn_again) Button btnAgain;
    //@BindView(R.id.ll_net_wrong) LinearLayout llNetWrong;
    //@BindView(R.id.btn_again) Button btnAgain;
    private Context mContext;
    private OptionAdapter adapter;
    private boolean isChoose;//是否已经做出了选择
    private boolean countDownIsOver;//答题倒计时是否结束了

    @BindView(R.id.civ_left_icon)
    CircleImageView civLeftIcon;
    @BindView(R.id.count_down_view)
    CountdownView countDownView;
    @BindView(R.id.civ_right_icon)
    CircleImageView civRightIcon;
    @BindView(R.id.ready_count_down_view)
    CountdownView readyCountDownView;
    private CardDisplayManager cardDisplayManager;
    private List<QuestionEntity.BodyBean.AnswersBean> optionBeans;
    private int rightKey;//正确答案的id
    private int questionId;//题目id
    private int chooseId;//选择的选项id
    //private boolean readyIsOver;//答题开始的倒计时 是否结束了
    private boolean otherIsUseYanshi;//对方是否使用了延时卡
    private boolean selfIsUseYanshi;//自己是否使用了延时卡
    private boolean isFirstShowYanshi = true;//是否是第一次显示延时的提示
    public static String paichuUrl;//排除道具的图片url
    private boolean otherIsRight;//对方是否答对了

    public AnswerCardLayout(Context context) {
        super(context);
        this.mContext = context;
        initView();
    }

    public AnswerCardLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView();
    }

    public void setCardDisplayManager(CardDisplayManager cardDisplayManager) {
        this.cardDisplayManager = cardDisplayManager;
    }

    /**
     * 初始化控件
     */
    private void initView() {
        LayoutInflater.from(mContext).inflate(R.layout.answer_card_layout, this);
        ButterKnife.bind(this);
        initCountView();
        optionList = findViewById(R.id.option_list);
        optionBeans = new ArrayList<>();
        adapter = new OptionAdapter(optionBeans);
        optionList.setAdapter(adapter);
        optionList.setOnItemClickListener((adapterView, view, i, l) -> {
            LogUtils.e("onItem:" + isChoose + "----cout:" + countDownIsOver);
            //如果已经选择过或者倒计时结束了，或者已经被排除卡排除的都不能点击
            if (isChoose || countDownIsOver || optionBeans.get(i).isRemoveCard()) return;
            isChoose = true;
            MediaUtil.getInstance(mContext).playeSmallVoice(R.raw.click_option);
            //点击选项后，延时卡和排除卡 不能使用
            cardDisplayManager.setIsCanRemove(false);
            cardDisplayManager.setCanUseDelay(false);
            optionBeans.get(i).setChoose(true);
            chooseId = optionBeans.get(i).getKey();
            adapter.notifyDataSetChanged();
            //点击选项后，上传答案
            cardDisplayManager.uploadAnswer(questionId, chooseId);
        });
    }

    private void initCountView() {
        readyCountDownView.setCountdownListener(new ReadyCountDownListener());
        countDownView.setCountdownListener(new AnswerCountDown());
    }

    /**
     * 开始ready界面的倒计时
     */
    public void startReadyCountDown() {
        readyCountDownView.start(5);
    }

    /**
     * 开始答题倒计时
     */
    private void startAnswerCountdown() {
        //if (readyCountDownView != null) {
        //    readyCountDownView.stop();
        //}
        countDownView.stop();
        countDownView.setTextColor(Color.WHITE);
        countDownView.setText("10");
        countDownView.setLong(true);
        countDownView.start(10);
    }

    /**
     * ready出现问题
     */
    //public void netWrong() {
    //    llNetWrong.setVisibility(VISIBLE);
    //    rlReadyLayout.setVisibility(GONE);
    //}

    /**
     * ready正常
     */
    //public void netRight() {
    //    llNetWrong.setVisibility(GONE);
    //    rlQestionMain.setVisibility(VISIBLE);
    //}

    //public void hideNetLayout() {
    //    llNetWrong.setVisibility(GONE);
    //}

    /**
     * 返回当前问题的id
     */
    public int getQid() {
        return questionId;
    }

    /**
     * 自己使用复活卡
     */
    public void reviveSelf() {
        civLeftIcon.setCircleBackgroundColor(getResources().getColor(R.color.right_bg));
        tvLeftRevive.setVisibility(VISIBLE);
        ivLeftRightOrWrong.setVisibility(GONE);
    }

    /**
     * 对方使用了延时卡
     */
    public void otherUseYanshi(String show) {
        countDownView.setVisibility(GONE);
        tvYanshiTips.setVisibility(VISIBLE);
        LogUtils.e("对方使用了延时卡：otherUseYanshi：" + show);
        tvPropTips.setVisibility(VISIBLE);
        tvPropTips.setText(show);
        tvYanshiTips.start(5);
        tvYanshiTips.setCountdownListener(progress -> {
            if (progress == 0) {
                tvYanshiTips.setVisibility(GONE);
                tvPropTips.setVisibility(GONE);
                LogUtils.e("延时卡结束：" + show);
                if (show.equals(Constant.YANSHI)) {
                    if (cardDisplayManager.getUserStatusEntity() != null) {
                        LogUtils.e("getUserStatusEntity is not  null");
                        onReceiveAnswer(cardDisplayManager.getUserStatusEntity());
                    } else {
                        LogUtils.e("getUserStatusEntity is null");
                    }
                }
            }
        });
    }

    /**
     * 对方使用复活卡
     */
    public void reviveRight() {
        civRightIcon.setCircleBackgroundColor(getResources().getColor(R.color.right_bg));
        tvRightRevive.setVisibility(VISIBLE);
        ivRightRightOrWrong.setVisibility(GONE);
    }

    /**
     * 收到下发题目消息,开始倒计时，绑定题目和选项到UI，
     */
    public void onReceiveQuestion(QuestionEntity entity) {
        ivRightRightOrWrong.setVisibility(GONE);
        ivLeftRightOrWrong.setVisibility(GONE);
        tvLeftRevive.setVisibility(GONE);
        tvRightRevive.setVisibility(GONE);
        tvYanshiTips.setVisibility(GONE);
        tvPropTips.setVisibility(GONE);
        countDownView.setVisibility(VISIBLE);
        otherIsUseYanshi = false;
        //getHandler().removeCallbacks(runnable);
        tvNumber.setText("第" + entity.getBody().getQnum() + "轮");
        tvQuestionContent.setText(entity.getBody().getQuestion());
        isChoose = false;
        countDownIsOver = false;
        selfIsUseYanshi = false;
        cardDisplayManager.setIsCanRemove(true);
        cardDisplayManager.setCanUseDelay(true);
        cardDisplayManager.setIsCanRevive(false);
        chooseId = 0;
        questionId = entity.getBody().getQid();
        LogUtils.e("questionId:" + questionId);
        rightKey = entity.getBody().getRight();
        optionBeans.clear();
        optionBeans.addAll(entity.getBody().getAnswers());
        adapter.notifyDataSetChanged();
        startAnswerCountdown();
//      LoadingDialog.getInstance((Activity) mContext).dismissDialog();
    }

    /**
     * 收到下发用户答题状态消息，修改头像显示对错图标
     */
    public void onReceiveAnswer(UserStatusEntity statusEntity) {
        LogUtils.e("收到答案-onReceiveAnswer:" + optionBeans.size());
        //刷新选项对错
        adapter.notifyDataSetChanged();
        //先判断是同一个问题,
        ivLeftRightOrWrong.setVisibility(VISIBLE);
        ivRightRightOrWrong.setVisibility(VISIBLE);
        civLeftIcon.setImageResource(R.color.transform);
        civRightIcon.setImageResource(R.color.transform);
        tvLeftRevive.setVisibility(GONE);
        tvRightRevive.setVisibility(GONE);
        tvPropTips.setVisibility(GONE);
        tvYanshiTips.setVisibility(GONE);
        //getHandler().removeCallbacks(runnable);
        for (int i = 0; i < statusEntity.getBody().getUsers().size(); i++) {
            if (statusEntity.getBody().getUsers().get(i).getUid().equals(Constant.OPENID)) {//自己
                if (statusEntity.getBody().getUsers().get(i).getStatus() == 1) {//答对
                    ivLeftRightOrWrong.setImageResource(R.mipmap.white_right_icon);
                    civLeftIcon.setCircleBackgroundColor(getResources().getColor(R.color.right_bg));
                    //如果答对则上报后台，后台会接着发题
                    cardDisplayManager.answerRight();
                    MediaUtil.getInstance(mContext).playeSmallVoice(R.raw.answer_right);
                } else {//答错
                    ivLeftRightOrWrong.setImageResource(R.mipmap.white_wrong_icon);
                    civLeftIcon.setCircleBackgroundColor(getResources().getColor(R.color.worng_bg));
                    //如果是回答错误，则会显示复活卡上面的提示可使用复活卡5秒钟
                    cardDisplayManager.answerWrong();
                    MediaUtil.getInstance(mContext).playeSmallVoice(R.raw.answer_wrong);
                }
            } else {//对手
                if (statusEntity.getBody().getUsers().get(i).getStatus() == 1) {//对手回答正确
                    ivRightRightOrWrong.setImageResource(R.mipmap.white_right_icon);
                    civRightIcon.setCircleBackgroundColor(
                            getResources().getColor(R.color.right_bg));
                    otherIsRight = true;
                } else {
                    otherUseYanshi(Constant.CHOOSEPROP);
                    otherIsRight = false;
                    ivRightRightOrWrong.setImageResource(R.mipmap.white_wrong_icon);
                    civRightIcon.setCircleBackgroundColor(
                            getResources().getColor(R.color.worng_bg));
                }
            }
        }
    }

    public boolean getOtherIsRight() {
        return otherIsRight;
    }

    public class OptionAdapter extends BaseAdapter {
        private List<QuestionEntity.BodyBean.AnswersBean> optionBeans;

        public OptionAdapter(List<QuestionEntity.BodyBean.AnswersBean> optionBeans) {
            this.optionBeans = optionBeans;
        }

        @Override
        public int getCount() {
            return optionBeans.size();
        }

        @Override
        public Object getItem(int i) {
            return i;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = LayoutInflater.from(mContext).inflate(R.layout.option_layout, null);
            TextView tvContent = view.findViewById(R.id.tv_answer);
            ImageView ivStatus = view.findViewById(R.id.iv_status_icon);
            tvContent.setText(optionBeans.get(i).getValue());
            ImageView ivProp = view.findViewById(R.id.iv_prop);
            if (countDownIsOver) {//如果倒计时结束，展示答案
                if (rightKey == optionBeans.get(i).getKey()) {//是正确的选项
                    if (optionBeans.get(i).isChoose()) {
                        view.setBackgroundResource(R.drawable.option_choose_bg);
                        tvContent.setTextColor(mContext.getResources().getColor(R.color.option_bg));
                    } else {
                        view.setBackgroundResource(R.drawable.option_bg);
                        tvContent.setTextColor(mContext.getResources().getColor(R.color.white));
                    }
                    ivStatus.setVisibility(VISIBLE);
                    ivStatus.setImageResource(R.mipmap.green_right_icon);
                } else {//如果该选项不是正确答案，则判断用户是否选择了改选项，如果选择了，则显示叉号
                    if (optionBeans.get(i).isChoose()) {
                        view.setBackgroundResource(R.drawable.option_choose_bg);
                        tvContent.setTextColor(mContext.getResources().getColor(R.color.option_bg));
                        ivStatus.setVisibility(VISIBLE);
                        tvContent.setTextColor(mContext.getResources().getColor(R.color.option_bg));
                        ivStatus.setImageResource(R.mipmap.red_wrong_icon);
                    } else {
                        ivStatus.setVisibility(GONE);
                        view.setBackgroundResource(R.drawable.option_bg);
                        tvContent.setTextColor(mContext.getResources().getColor(R.color.white));
                    }
                }
            } else {//倒计时未结束，则展示选项和点击选项之后的状态
                if (isChoose) {//表示点击了
                    if (optionBeans.get(i).isChoose()) {//点击了选项，改选项背景变为白色
                        view.setBackgroundResource(R.drawable.option_choose_bg);
                        tvContent.setTextColor(mContext.getResources().getColor(R.color.option_bg));
                    } else {//未选择，颜色不变
                        view.setBackgroundResource(R.drawable.option_bg);
                        tvContent.setTextColor(mContext.getResources().getColor(R.color.white));
                    }
                } else {//未点击，正常显示
                    view.setBackgroundResource(R.drawable.option_bg);
                    tvContent.setTextColor(mContext.getResources().getColor(R.color.white));
                }
            }

            if (optionBeans.get(i).isRemoveCard()) {
                ivProp.setVisibility(VISIBLE);
                ImageLoader.load(mContext, paichuUrl, 0, ivProp);
                tvContent.setTextColor(mContext.getResources().getColor(R.color.white_30));
            } else {
                if (optionBeans.get(i).isChoose()) {
                    tvContent.setTextColor(mContext.getResources().getColor(R.color.option_bg));
                } else {
                    tvContent.setTextColor(mContext.getResources().getColor(R.color.white));
                }
                ivProp.setVisibility(GONE);
            }

            return view;
        }
    }

    //private void startAnswerGame() {
    //    countDownView.setVisibility(View.VISIBLE);
    //    rlReadyLayout.setVisibility(GONE);
    //    rlQestionMain.setVisibility(VISIBLE);
    //    //hideNetLayout();
    //}

    /**
     * 延时控件是否可见
     */
    public boolean getOtherYanshiIsOver() {
        return tvYanshiTips.getVisibility() == VISIBLE;
    }

    /**
     * 使用一张排除卡，排除一个错误选项
     */
    public void useRemoveCard() {
        if (optionBeans == null) return;
        List<Integer> custom = new ArrayList<>();
        for (int i = 0; i < optionBeans.size(); i++) {
            if (optionBeans.get(i).getKey() != rightKey) {
                //填入错误答案的位置
                custom.add(i);
                LogUtils.e("array--i:" + i);
            } else {
                LogUtils.e("array-right:" + i);
            }
        }
        int random = new Random().nextInt(2);
        optionBeans.get(custom.get(random)).setRemoveCard(true);
        adapter.notifyDataSetChanged();
    }

    /**
     * 自己使用了延时卡
     */
    public void useDelayCard() {
        tvSelfYanshi.setVisibility(VISIBLE);
        countDownView.setVisibility(VISIBLE);
        selfIsUseYanshi = true;
        //countDownView.stop();
        //countDownView.start((int) (countDownView.getTime() + 5));
    }

    public void stopCount() {
        countDownView.stop();
        //readyCountDownView.stop();
    }

    /**
     * 设置头像可见
     */
    public void setAvatarVivible() {
        civLeftIcon.setVisibility(VISIBLE);
        civRightIcon.setVisibility(VISIBLE);
    }

    /**
     * 等待进入倒计时监听
     */
    private class ReadyCountDownListener implements CountdownView.OnCountdownListener {
        @Override
        public void onProgress(long progress) {
            readyCountDownView.setText(progress + "");
            MediaUtil.getInstance(mContext).playeSmallVoice(R.raw.answer_wrong);
        }
    }

    private ReadyOverCallback readyOverCallback;

    public void setReadyOverCallback(ReadyOverCallback readyOverCallback) {
        this.readyOverCallback = readyOverCallback;
    }

    public interface ReadyOverCallback {
        void countDownIsOver();
    }
    public void setLeftIcon(String imgUrl) {
        ImageLoader.load(mContext, imgUrl, R.mipmap.gold_icon, civLeftIcon);
    }

    public void setRightIcon(String imgUrl) {
        ImageLoader.load(mContext, imgUrl, R.mipmap.gold_icon, civRightIcon);
    }

    public boolean isOtherIsUseYanshi() {
        return otherIsUseYanshi;
    }

    public void setOtherIsUseYanshi(boolean otherIsUseYanshi) {
        this.otherIsUseYanshi = otherIsUseYanshi;
    }

    public boolean isFirstShowYanshi() {
        return isFirstShowYanshi;
    }

    public void setFirstShowYanshi(boolean firstShowYanshi) {
        isFirstShowYanshi = firstShowYanshi;
    }

    public boolean isSelfIsUseYanshi() {
        return selfIsUseYanshi;
    }

    public void setSelfIsUseYanshi(boolean selfIsUseYanshi) {
        this.selfIsUseYanshi = selfIsUseYanshi;
    }

    /**
     * 答题倒计时
     */
    private class AnswerCountDown implements CountdownView.OnCountdownListener {

        @Override
        public void onProgress(long progress) {
            if (progress == 3) {
                if (tvSelfYanshi.getVisibility() == GONE) {
                    countDownView.setTextColor(
                            getResources().getColor(R.color.count_down_text_color));
                }
                if (!isChoose && isFirstShowYanshi) {//如果倒计时到3时还没有选择选项，则提示使用延时道具的弹窗
                    isFirstShowYanshi = false;
                    cardDisplayManager.showYanshiPopup();
                }
                MediaUtil.getInstance(mContext).playeSmallVoice(R.raw.count_down);
            } else if (progress == 2 || progress == 1 || progress == 0) {
                if (tvSelfYanshi.getVisibility() == GONE) {
                    countDownView.setTextColor(
                            getResources().getColor(R.color.count_down_text_color));
                }
            } else {
                MediaUtil.getInstance(mContext).playeSmallVoice(R.raw.ding);
                countDownView.setTextColor(getResources().getColor(R.color.white));
            }
            countDownView.setText(progress + "");
            if (progress <= 0) {
                countDownView.setTextColor(getResources().getColor(R.color.count_down_text_color));
                countDownView.stop();
                /**
                 * 当使用延时卡后，第一次十秒倒计时结束后还能点击选项
                 */
                if (countDownView.isLong()) {//当10秒倒计时结束时
                    if (!selfIsUseYanshi) {//如果自己没有使用延时卡
                        //设置选项不可点击
                        countDownIsOver = true;
                        //答题结束后回调给CardDisplayManager，显示双方选择的对错
                        readyOverCallback.countDownIsOver();
                        //设置延时卡不可使用
                        cardDisplayManager.setCanUseDelay(false);
                        //设置排除卡不可使用
                        cardDisplayManager.setIsCanRemove(false);
                        if (!isChoose) {//如果没有点击选项，则默认上传答案id为0
                            chooseId = 0;
                            cardDisplayManager.uploadAnswer(questionId, chooseId);
                        }
                    } else {//如果自己使用了延时卡
                        tvSelfYanshi.setVisibility(GONE);
                        countDownView.setVisibility(VISIBLE);
                        countDownView.start(5);
                    }
                } else {//如果是5秒倒计时结束
                    LogUtils.e("倒计时5秒结束");
                    //设置选项不可点击
                    countDownIsOver = true;
                    //答题结束后回调给CardDisplayManager，显示双方选择的对错
                    readyOverCallback.countDownIsOver();
                    //设置延时卡不可使用
                    cardDisplayManager.setCanUseDelay(false);
                    //设置排除卡不可使用
                    cardDisplayManager.setIsCanRemove(false);
                    if (!isChoose) {//如果没有点击选项，则默认上传答案id为0
                        chooseId = 0;
                        cardDisplayManager.uploadAnswer(questionId, chooseId);
                    }
                }
            }
        }
    }

    /**
     * 返回答题倒计时 是否结束
     */
    public boolean getCountdownIsOver() {
        return countDownIsOver;
    }
}
